//
//  SEGWindmillRefreshHeader.m
//  RefreshDemo
//
//  Created by Clavis on 2019/1/2.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "SEGWindmillRefreshHeader.h"

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

@interface SEGWindmillRefreshHeader ()
@property (nonatomic, assign) CGFloat insetTDelta;
@end

@implementation SEGWindmillRefreshHeader

#pragma mark - 构造方法
+ (instancetype)headerWithRefreshingBlock:(SEGWindmillComponentRefreshBeginBlock)refreshingBlock {
    SEGWindmillRefreshHeader *header = [[self alloc] init];
    header.refreshingBlock = refreshingBlock;
    return header;
}


#pragma mark - 覆盖父类的方法
- (void)prepare {
    [super prepare];
    
    // 设置高度
    self.height = SEGRefreshHeaderHeight;
}

- (void)placeSubviews {
    [super placeSubviews];
    // 设置y值(当自己的高度发生改变了，肯定要重新调整Y值，所以放到placeSubviews方法中设置y值)
    self.y = - self.height - self.ignoredScrollViewContentInsetTop;
}

- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change {
    [super scrollViewContentOffsetDidChange:change];
    
    // 在刷新的refreshing状态
    if (self.state == SEGRefreshStateRefreshing) {
        // 暂时保留
        if (self.window == nil) return;
        
        // sectionheader停留解决
        CGFloat insetT = - self.scrollView.seg_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.seg_offsetY : _scrollViewOriginalInset.top;
        insetT = insetT > self.height + _scrollViewOriginalInset.top ? self.height + _scrollViewOriginalInset.top : insetT;
        self.scrollView.seg_insetT = insetT;
        
        self.insetTDelta = _scrollViewOriginalInset.top - insetT;
        return;
    }
    
    // 跳转到下一个控制器时，contentInset可能会变
    _scrollViewOriginalInset = self.scrollView.seg_inset;
    
    // 当前的contentOffset
    CGFloat offsetY = self.scrollView.seg_offsetY;
    // 头部控件刚好出现的offsetY
    CGFloat happenOffsetY = - self.scrollViewOriginalInset.top;
    
    // 如果是向上滚动到看不见头部控件，直接返回
    // >= -> >
    if (offsetY > happenOffsetY) return;
    
    // 普通 和 即将刷新 的临界点
    CGFloat normal2pullingOffsetY = happenOffsetY - self.height;
    CGFloat pullingPercent = (happenOffsetY - offsetY) / self.height;
    
    if (self.scrollView.isDragging) { // 如果正在拖拽
        self.pullingPercent = pullingPercent;
        if (self.state == SEGRefreshStateIdle && offsetY < normal2pullingOffsetY) {
            // 转为即将刷新状态
            self.state = SEGRefreshStatePulling;
        } else if (self.state == SEGRefreshStatePulling && offsetY >= normal2pullingOffsetY) {
            // 转为普通状态
            self.state = SEGRefreshStateIdle;
        }
    } else if (self.state == SEGRefreshStatePulling) {// 即将刷新 && 手松开
        // 开始刷新
        [self beginRefreshing];
    } else if (pullingPercent < 1) {
        self.pullingPercent = pullingPercent;
    }
}

- (void)setState:(SEGRefreshState)state
{
    SEGRefreshCheckState
    
    // 根据状态做事情
    if (state == SEGRefreshStateIdle) {
        if (oldState != SEGRefreshStateRefreshing) return;
        
        // 恢复inset和offset
        [UIView animateWithDuration:SEGRefreshSlowAnimationDuration animations:^{
            self.scrollView.seg_insetT += self.insetTDelta;
            
            // 自动调整透明度
            if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
        } completion:^(BOOL finished) {
            self.pullingPercent = 0.0;
        }];
    } else if (state == SEGRefreshStateRefreshing) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:SEGRefreshFastAnimationDuration animations:^{
                CGFloat top = self.scrollViewOriginalInset.top + self.height;
                // 增加滚动区域top
                self.scrollView.seg_insetT = top;
                // 设置滚动位置
                CGPoint offset = self.scrollView.contentOffset;
                offset.y = -top;
                [self.scrollView setContentOffset:offset animated:NO];
            } completion:^(BOOL finished) {
                [self executeRefreshingCallback];
            }];
        });
    }
   
}

@end
